package com.mine.photohandler.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.ColorInt;
import androidx.core.graphics.ColorUtils;
import androidx.appcompat.app.AppCompatActivity;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.mine.photohandler.R;
import com.mine.photohandler.util.ActivityManager;
import com.mine.photohandler.util.MyToast;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


/**
 * Activity的基类，项目中所有Activity应该继承于该类
 */
public abstract class BaseAppCompatActivity extends AppCompatActivity {

    protected Resources mResources;
    protected AssetManager mAssets;
    protected MyToast toast;
    protected View parentView;

    protected Context context;
    protected Activity activity;
    public boolean isBackExit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.addActivity(this);

        parentView = getLayoutInflater().inflate(contentView(), null);
        setContentView(contentView());
        context = this;
        activity = this;

        toast = new MyToast(this);

        mResources = getResources();
        mAssets = getAssets();
        hideStateView();
        initViews();
        initEvents();
        loadDatas(getIntent());
        update_version();

    }

    /**
     * 加载数据方法
     */
    protected void loadDatas(Intent intent) {

    }

    /**
     * 初始化
     */
    protected void initViews() {

    }

    /**
     *
     */
    protected void initEvents() {

    }

    /**
     * 版本升级
     */
    public void update_version() {

    }

    /**
     * 布局Id
     *
     * @return
     */
    protected abstract int contentView();

    /**
     * 启动方式
     *
     * @param activity    启动的Activity
     * @param isExit      是否退出
     * @param bundle      传参
     * @param requestCode 请求码
     */
    public void startActivity(Class<?> activity, boolean isExit, Bundle bundle,
                              int requestCode) {

        Intent intent = new Intent(this, activity);
        if (bundle != null) {
            intent.putExtras(bundle);
        }

        startActivityForResult(intent, requestCode);

        if (isExit) {
            finish();
        }
    }

    public void startActivity(Class<?> activity, boolean isExit, int requestCode) {
        startActivity(activity, isExit, null, requestCode);
    }

    public void startActivity(Class<?> activity, boolean isExit, Bundle bundle) {
        startActivity(activity, isExit, bundle, -1);
    }

    public void startActivity(Class<?> activity, boolean isExit) {
        startActivity(activity, isExit, null);
    }

    /**
     * 获取EditText的输入内容
     *
     * @param editText
     * @return
     */
    public String getEditTextStr(EditText editText) {
        return editText.getText().toString().trim();
    }

    /**
     * 提示信息
     *
     * @param msg
     */
    public void showMsg(String msg) {
        if (msg != null) {
            toast.show(msg, 10);
        }
    }

    /**
     * 提示信息
     *
     * @param msg
     */
    public void showMsg(int msg) {
        toast.show(msg, 10);
    }

    /**
     * [是否连续两次返回退出]
     */
    public void setBackExit(boolean isBackExit) {
        this.isBackExit = isBackExit;
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (isBackExit) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    ActivityManager.removeAllActivity();
                }
            } else {
                Activity activity = getTopActivity();
                if (null != activity) {
                    ActivityManager.removeActivity(activity);
                    activity.finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @SuppressLint("InlinedApi")
    public void startActivityNewTask(Class<?> activity) {
        Intent intent = new Intent(this, activity);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        toast.cancel();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //注：回调 3
        return super.dispatchTouchEvent(event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.removeActivity(this);
    }

    /**
     * 获取栈顶Activity
     *
     * @return 栈顶Activity
     */
    public static Activity getTopActivity() {
        try {
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = null;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                activities = (HashMap) activitiesField.get(activityThread);
            } else {
                activities = (ArrayMap) activitiesField.get(activityThread);
            }
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    return (Activity) activityField.get(activityRecord);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过设置全屏，设置状态栏透明
     *
     * @param activity
     */
    protected void fullScreen(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.BLACK);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
                attributes.flags |= flagTranslucentStatus;
//                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }




    /**
     * Android 6.0 以上设置状态栏颜色
     */
    public void setStatusBar(@ColorInt int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // 如果亮色，设置状态栏文字为黑色
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | (isLightColor(color) ? View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR : View.SYSTEM_UI_FLAG_VISIBLE);
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor( Color.TRANSPARENT);
                //导航栏颜色也可以正常设置
//                        window.setNavigationBarColor(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
                attributes.flags |= flagTranslucentStatus;
//                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }

    /**
     * 判断颜色是不是亮色
     *
     * @param color
     * @return
     * @from https://stackoverflow.com/questions/24260853/check-if-color-is-dark-or-light-in-android
     */
    private boolean isLightColor(@ColorInt int color) {
        return ColorUtils.calculateLuminance(color) >= 0.5;
    }

    public void hideStateView(){
        try{
            View view = findViewById(R.id.view_state);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                if (view != null){
                    view.setVisibility(View.GONE);
                }
            }
        }catch (Exception e){

        }
    }
}


